package own.stu.jobgib.playown.alg.heap;

import jdk.nashorn.internal.ir.CallNode;

public class HeapOp {
    int[] queue;
    int size;

    private void heapify(){
        for(int i = (size >>> 1) - 1; i >= 0; i --){
            siftDown(i, queue[i]);
        }
    }

    private void siftDown(int k, int ele) {
        int half = size >>> 1; // loop while a non-leaf
        while (k < half) {
            int child = (k << 1) + 1; // assume left child is least
            int c = queue[child];
            int right = child + 1;
            if (right < size && c > queue[right]) {
                c = queue[child = right];
            }
            if (ele <= c) {
                break;
            }
            queue[k] = c;
            k = child;
        }

        queue[k] = ele;
    }

    public boolean add(int e){
        int i = size;
        size += 1;
        if(i == 0){
            queue[0] = e;
        }else{
            siftUp(i, e);
        }
        return true;
    }

    private void siftUp(int k, int e) {
        while(k > 0){
            int p = (k - 1) >>> 1;
            int pV = queue[p];
            if(e >= pV)
                break;
            queue[k] = p;
            k = p;
        }
        queue[k] = e;
    }
}
